import router from '@/router'
import store from '@/store'
import {getToken} from '@/utils/session_storage'

const whiteList = ['/login', '/register', '/logout']

router.beforeEach((to, from, next) => {
    if (getToken()) {
        if (to.path === '/login') {
            next({path: '/'})
        } else {
            // 如果用户F5刷新页面，vue实例会重新创建，store中的数据都会重置
            if (store.getters.menus.length === 0) {
                store.dispatch('GenerateRoutes').then(accessRoutes => {
                    router.addRoutes(accessRoutes) // 动态添加可访问路由表
                })
            }
            next()
        }
    } else {
        // 没有token
        if (whiteList.indexOf(to.path) !== -1) {
            // 在免登录白名单，直接进入
            next()
        } else {
            next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
        }
    }
})

router.afterEach(() => {
})
